package vaccine.appointment.system.family.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vaccine.appointment.system.common.enums.DelFlgEnum;
import vaccine.appointment.system.common.errorcode.CommonErrorCode;
import vaccine.appointment.system.common.errorcode.ErrorCode;
import vaccine.appointment.system.common.exception.CommonException;
import vaccine.appointment.system.family.dataobject.Family;
import vaccine.appointment.system.family.enums.FamilyRelationshipEnum;
import vaccine.appointment.system.family.mapper.FamilyMapper;
import vaccine.appointment.system.family.service.FamilyService;
import vaccine.appointment.system.family.vo.AddFamilyRequest;
import vaccine.appointment.system.family.vo.FamilyInfoVO;
import vaccine.appointment.system.person.dataobject.Person;
import vaccine.appointment.system.person.mapper.PersonMapper;

import java.util.ArrayList;
import java.util.List;

/**
 * 家庭服务实现类
 */
@Service
public class FamilyServiceImpl implements FamilyService {

    @Autowired
    private FamilyMapper familyMapper;

    @Autowired
    private PersonMapper personMapper;

    @Override
    public Boolean add(Family family) {
        familyMapper.insert(family);
        return true;
    }

    @Override
    public Boolean delete(Integer id) {
        Family family = familyMapper.selectById(id);
        familyMapper.updateById(family);
        return true;
    }

    @Override
    public Boolean update(Family family) {
        familyMapper.updateById(family);
        return true;
    }

    @Override
    public Family selectById(Integer id) {
        return familyMapper.selectById(id);
    }

    /**
     * 添加家属
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addFamily(Integer userId, AddFamilyRequest request) {
        // 1. 检查身份证号是否已存在
        QueryWrapper<Person> personQueryWrapper = new QueryWrapper<>();
        personQueryWrapper.eq("id_num", request.getIdNum());
        personQueryWrapper.eq("del_flg", DelFlgEnum.NOT_DELETED.getCode());
        Person existingPerson = personMapper.selectOne(personQueryWrapper);

        Person person;
        if (existingPerson != null) {
            // 身份证号已存在，使用现有的Person记录
            person = existingPerson;
        } else {
            // 创建新的Person记录
            person = new Person();
            person.setName(request.getName());
            person.setAge(request.getAge());
            person.setIdNum(request.getIdNum());
            person.setDelFlg(DelFlgEnum.NOT_DELETED.getCode());
            personMapper.insert(person);
        }

        // 2. 检查是否已经添加过该家属
        QueryWrapper<Family> familyQueryWrapper = new QueryWrapper<>();
        familyQueryWrapper.eq("user_id", userId);
        familyQueryWrapper.eq("person_id", person.getId());
        familyQueryWrapper.eq("del_flg", DelFlgEnum.NOT_DELETED.getCode());
        Family existingFamily = familyMapper.selectOne(familyQueryWrapper);

        if (existingFamily != null) {
            throw new CommonException(new ErrorCode(400, "该家属已添加"));
        }

        // 3. 创建Family关系
        Family family = new Family();
        family.setUserId(userId);
        family.setPersonId(person.getId());
        family.setRelationship(request.getRelationship());
        family.setDelFlg(DelFlgEnum.NOT_DELETED.getCode());

        int result = familyMapper.insert(family);
        return result > 0;
    }

    /**
     * 查询家属列表
     */
    @Override
    public List<FamilyInfoVO> getFamilyList(Integer userId) {
        // 1. 查询用户的所有家属关系
        QueryWrapper<Family> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("del_flg", DelFlgEnum.NOT_DELETED.getCode());
        List<Family> familyList = familyMapper.selectList(queryWrapper);

        // 2. 组装返回数据
        List<FamilyInfoVO> result = new ArrayList<>();
        for (Family family : familyList) {
            Person person = personMapper.selectById(family.getPersonId());
            if (person != null && person.getDelFlg().equals(DelFlgEnum.NOT_DELETED.getCode())) {
                FamilyInfoVO vo = new FamilyInfoVO();
                vo.setFamilyId(family.getId());
                vo.setPersonId(person.getId());
                vo.setName(person.getName());
                vo.setAge(person.getAge());
                vo.setIdNum(person.getIdNum());
                vo.setRelationship(family.getRelationship());
                vo.setRelationshipDesc(FamilyRelationshipEnum.getDescByCode(family.getRelationship()));
                result.add(vo);
            }
        }

        return result;
    }

    /**
     * 删除家属
     */
    @Override
    public Boolean deleteFamily(Integer userId, Integer familyId) {
        // 1. 查询家属关系
        Family family = familyMapper.selectById(familyId);
        if (family == null || family.getDelFlg().equals(DelFlgEnum.DELETED.getCode())) {
            throw new CommonException(CommonErrorCode.NOT_FOUND);
        }

        // 2. 验证是否属于当前用户
        if (!family.getUserId().equals(userId)) {
            throw new CommonException(CommonErrorCode.FORBIDDEN);
        }

        // 3. 逻辑删除
        family.setDelFlg(DelFlgEnum.DELETED.getCode());
        int result = familyMapper.updateById(family);

        return result > 0;
    }
}
